import React, {useEffect, useState} from "react";
import {Button, Col, DatePicker, Form, Input, message, Modal, Row} from "antd";
import type {Result} from "@/types/result";
import enterpriseApi from "@/api/enterpriseApi.ts";
import {Enterprise} from "@/types/resp/enterprise";

interface EnterpriseAddProps {
  visible: boolean;
  id: number;
  onCloseEnterpriseAdd: () => void;
}

const EnterpriseAdd: React.FC<EnterpriseAddProps> = ({visible, id, onCloseEnterpriseAdd}) => {

  const [form] = Form.useForm<Enterprise>();
  const [messageApi, messageContextHolder] = message.useMessage();

  const rules = {
    name: [
      { required: true, message: '请输入企业名称' }
    ],
    registeredAddress: [
      { required: true, message: '请输入注册地址' }
    ],
    contactPhone: [
      { required: true, message: '请输入联系电话' }
    ],
    email: [
      { required: true, message: '请输入邮箱' }
    ],
    taxIdentificationNumber: [
      { required: true, message: '请输入纳税识别号' }
    ],
  };

  let enterpriseForm: Partial<Enterprise> = {}

  const [title, setTitle] = useState('新增企业信息');

  useEffect(() => {
    if (!visible) {
      return
    }
    if (id) {
      setTitle('编辑企业信息')
      initEnterpriseFormById(id)
    } else {
      setTitle('新增企业信息')
      form.resetFields();
    }
  }, [visible]);

  const initEnterpriseFormById = async (id: number) => {
    const resp: Result<Enterprise> = await enterpriseApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      enterpriseForm = resp.data
      form.setFieldsValue(resp.data);
    }
  }

  const onSave = async () => {
    try {
      await form.validateFields()

      let enterprise2Save:Enterprise = form.getFieldsValue()
      if (id) {
        enterprise2Save = Object.assign(enterpriseForm, enterprise2Save)
      }
      const resp: Result<void> = await enterpriseApi.save(enterprise2Save);
      if (!resp || resp.code !== 1) {
        messageApi.error('保存失败:' + (resp.msg ? resp.msg : '未知异常'));
        return
      }
      messageApi.success('保存成功');
      onBack()
    } catch (error) {
      console.error('There was an error submitting the form!', error);
    }
  };

  const onReset = () => {
    setTitle('新增企业信息')
    form.resetFields();
  };
  

  const onBack = () => {
    onCloseEnterpriseAdd()
  };

  const addFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onSave}>保存</Button>
      <Button onClick={onReset} style={{marginLeft: 'var(--button-margin-left)'}}>重置</Button>
      <Button type="primary" onClick={onBack} style={{marginLeft: 'var(--button-margin-left)'}}>关闭</Button>
    </div>
  );

  return (
    <Modal title={title} open={visible} onCancel={onCloseEnterpriseAdd} width={'var(--modal-width)'}
        footer={addFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      {messageContextHolder}
      <Form form={form} name="enterpriseForm" labelCol={{span: 6}}>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="name" label="企业名称" rules={rules.name}>
              <Input maxLength={64} placeholder="请输入企业名称"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="establishmentDate" label="成立日期">
              <DatePicker/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="registeredAddress" label="注册地址" rules={rules.registeredAddress}>
              <Input maxLength={255} placeholder="请输入注册地址"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="contactPhone" label="联系电话" rules={rules.contactPhone}>
              <Input maxLength={64} placeholder="请输入联系电话"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="email" label="邮箱" rules={rules.email}>
              <Input maxLength={64} placeholder="请输入邮箱"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="officialWebsite" label="官网网址">
              <Input maxLength={255} placeholder="请输入官网网址"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="taxIdentificationNumber" label="纳税识别号" rules={rules.taxIdentificationNumber}>
              <Input maxLength={255} placeholder="请输入纳税识别号"/>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  )
}

export default EnterpriseAdd;
